package com.xzzz.irda.guardcat.server.util;


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.databind.JsonNode;
import com.xzzz.common.base.exception.XzException500;
import com.xzzz.common.base.util.json.JsonUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;

/**
 * @author xzzz
 */
@Slf4j
@SuppressWarnings("all")
public class PhoneMsgUtil {

    private static final String SYS_DOMAIN = "dysmsapi.aliyuncs.com";
    private static final String SYS_ACTION = "SendSms";
    private static final String SYS_VERSION = "2017-05-25";

    private static final String QUERY_PARAM_REGION_ID = "cn-hangzhou";
    private static final String QUERY_PARAM_SIGN_NAME = "瞧瞧科技";

    private static final String ACCESS_KEY_ID = "LTAI4G2jfv22NdmrEdcjcnz8";
    private static final String SECRET = "ITPSlEPynE0vM6t3eiYHgiWDRdx43h";

    private static final IAcsClient CLIENT;

    public static void main(String[] args) {
        PhoneMsg phoneMsg = new PhoneMsg();
        phoneMsg.setReceiverPhone("18734543171");
        phoneMsg.setTemplate("SMS_235495483");
        phoneMsg.setContent("{" +
                "\"system\":\"" + "usercenter-prod-1" + "\"," +
                "\"type\":\"" + "刷新小程序TOKEN异常" + "\"" +
            "}");
        phoneMsg.setId(UUID.randomUUID().toString());
        PhoneMsgUtil.send(phoneMsg);
    }

    static {
        DefaultProfile profile = DefaultProfile.getProfile(QUERY_PARAM_REGION_ID, ACCESS_KEY_ID, SECRET);
        CLIENT = new DefaultAcsClient(profile);
    }

    public static void send(PhoneMsg phoneMsg) {
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(SYS_DOMAIN);
        request.setSysAction(SYS_ACTION);
        request.setSysVersion(SYS_VERSION);

        request.putQueryParameter("RegionId", QUERY_PARAM_REGION_ID);
        // 签名
        request.putQueryParameter("SignName", QUERY_PARAM_SIGN_NAME);
        // 模板 ID
        request.putQueryParameter("TemplateCode", phoneMsg.getTemplate());
        // 手机号
        request.putQueryParameter("PhoneNumbers", phoneMsg.getReceiverPhone());
        // 模板参数 json 字符串
        request.putQueryParameter("TemplateParam", phoneMsg.getContent());
        // 外部业务 ID
        request.putQueryParameter("OutId", phoneMsg.getId());

        try {
            CommonResponse resp = CLIENT.getCommonResponse(request);
            if (resp == null) {
                throw new XzException500("[阿里短信] 发送短信失败,无响应体");
            }

            JsonNode jsonNode = JsonUtil.toJsonNode(resp.getData());
            if (jsonNode.get("Code") == null || !AliMsgResultEnum.OK.getCode().equals(jsonNode.get("Code").asText())) {
                throw new XzException500(jsonNode.get("Message").asText());
            }
        } catch (ClientException e) {
            log.error("[阿里短信] 发送短信时异常, 内容:{}, 错误信息:{}", phoneMsg.toString(), e.getMessage());
            e.printStackTrace();
        }
    }

    @Data
    public static class PhoneMsg {
        /** 外部ID */
        private String id;
        /** 发送具体类型 */
        private String template;
        /** 发送内容 */
        private String content;
        /** 手机号 */
        private String receiverPhone;
    }

    enum AliMsgResultEnum {

        /**
         * 阿里短信发送响应信息封装
         */
        OK("OK", "OK", ""),
        SMS_SIGNATURE_SCENE_ILLEGAL("isv.SMS_SIGNATURE_SCENE_ILLEGAL", "短信所使用签名场景非法", ""),
        EXTEND_CODE_ERROR("isv.EXTEND_CODE_ERROR", "扩展码使用错误，相同的扩展码不可用于多个签名", ""),
        DOMESTIC_NUMBER_NOT_SUPPORTED("isv.DOMESTIC_NUMBER_NOT_SUPPORTED", "国际/港澳台消息模板不支持发送境内号码", ""),
        DENY_IP_RANGE("isv.DENY_IP_RANGE", "源IP地址所在的地区被禁用", ""),
        DAY_LIMIT_CONTROL("isv.DAY_LIMIT_CONTROL", "触发日发送限额", ""),
        SMS_CONTENT_ILLEGAL("isv.SMS_CONTENT_ILLEGAL", "短信内容包含禁止发送内容", ""),
        SMS_SIGN_ILLEGAL("isv.SMS_SIGN_ILLEGAL", "签名禁止使用", ""),
        RAM_PERMISSION_DENY("isp.RAM_PERMISSION_DENY", "RAM权限DENY", ""),
        OUT_OF_SERVICE("isv.OUT_OF_SERVICE", "业务停机", ""),
        PRODUCT_UN_SUBSCRIPT("isv.PRODUCT_UN_SUBSCRIPT", "未开通云通信产品的阿里云客户", ""),
        PRODUCT_UNSUBSCRIBE("isv.PRODUCT_UNSUBSCRIBE", "产品未开通", ""),
        ACCOUNT_NOT_EXISTS("isv.ACCOUNT_NOT_EXISTS", "账户不存在", ""),
        ACCOUNT_ABNORMAL("isv.ACCOUNT_ABNORMAL", "账户异常", ""),
        SMS_TEMPLATE_ILLEGAL("isv.SMS_TEMPLATE_ILLEGAL", "短信模版不合法", ""),
        SMS_SIGNATURE_ILLEGAL("isv.SMS_SIGNATURE_ILLEGAL", "短信签名不合法", ""),
        INVALID_PARAMETERS("isv.INVALID_PARAMETERS", "参数异常", ""),
        SYSTEM_ERROR("isp.SYSTEM_ERROR", "系统错误", ""),
        MOBILE_NUMBER_ILLEGAL("isv.MOBILE_NUMBER_ILLEGAL", "非法手机号", ""),
        MOBILE_COUNT_OVER_LIMIT("isv.MOBILE_COUNT_OVER_LIMIT", "手机号码数量超过限制", ""),
        TEMPLATE_MISSING_PARAMETERS("isv.TEMPLATE_MISSING_PARAMETERS", "模版缺少变量", ""),
        BUSINESS_LIMIT_CONTROL("isv.BUSINESS_LIMIT_CONTROL", "业务限流", "短信发送频繁,请稍后再试"),
        INVALID_JSON_PARAM("isv.INVALID_JSON_PARAM", "JSON参数不合法，只接受字符串值", ""),
        BLACK_KEY_CONTROL_LIMIT("isv.BLACK_KEY_CONTROL_LIMIT", "黑名单管控", ""),
        PARAM_LENGTH_LIMIT("isv.PARAM_LENGTH_LIMIT", "参数超出长度限制", ""),
        PARAM_NOT_SUPPORT_URL("isv.PARAM_NOT_SUPPORT_URL", "不支持URL", ""),
        AMOUNT_NOT_ENOUGH("isv.AMOUNT_NOT_ENOUGH", "账户余额不足", ""),
        TEMPLATE_PARAMS_ILLEGAL("isv.TEMPLATE_PARAMS_ILLEGAL", "模版变量里包含非法关键字", ""),
        SignatureDoesNotMatch("SignatureDoesNotMatch", "Specified signature is not matched with our calculation.", ""),
        InvalidTimeStampExpired("InvalidTimeStamp.Expired", "Specified time stamp or date value is expired.", ""),
        SignatureNonceUsed("SignatureNonceUsed", "Specified signature nonce was used already.", ""),
        InvalidVersion("InvalidVersion", "Specified parameter Version is not valid.", ""),
        InvalidActionNotFound("InvalidAction.NotFound", "Specified api is not found, please check your url and method", ""),
        SIGN_COUNT_OVER_LIMIT("isv.SIGN_COUNT_OVER_LIMIT", "一个自然日中申请签名数量超过限制。", ""),
        TEMPLATE_COUNT_OVER_LIMIT("isv.TEMPLATE_COUNT_OVER_LIMIT", "一个自然日中申请模板数量超过限制。", ""),
        SIGN_NAME_ILLEGAL("isv.SIGN_NAME_ILLEGAL", "签名名称不符合规范。", ""),
        SIGN_FILE_LIMIT("isv.SIGN_FILE_LIMIT", "签名认证材料附件大小超过限制。", ""),
        SIGN_OVER_LIMIT("isv.SIGN_OVER_LIMIT", "签名字符数量超过限制。", ""),
        TEMPLATE_OVER_LIMIT("isv.TEMPLATE_OVER_LIMIT", "签名字符数量超过限制。", ""),
        SIGNATURE_BLACKLIST("SIGNATURE_BLACKLIST", "签名黑名单", ""),
        SHORTURL_OVER_LIMIT("isv.SHORTURL_OVER_LIMIT", "一天创建短链数量超过限制", ""),
        NO_AVAILABLE_SHORT_URL("isv.NO_AVAILABLE_SHORT_URL", "无有效短链", ""),
        SHORTURL_NAME_ILLEGAL("isv.SHORTURL_NAME_ILLEGAL", "短链名称非法", ""),
        SOURCEURL_OVER_LIMIT("isv.SOURCEURL_OVER_LIMIT", "原始链接字符数量超过限制", ""),
        SHORTURL_TIME_ILLEGAL("isv.SHORTURL_TIME_ILLEGAL", "短链有效期期限超过限制", ""),
        PHONENUMBERS_OVER_LIMIT("isv.PHONENUMBERS_OVER_LIMIT", "上传手机号个数超过上限", ""),
        SHORTURL_STILL_AVAILABLE("isv.SHORTURL_STILL_AVAILABLE", "原始链接生成的短链仍在有效期内", ""),
        SHORTURL_NOT_FOUND("isv.SHORTURL_NOT_FOUND", "没有可删除的短链", ""),
        ERROR_SIGN_NOT_MODIFY("isv.ERROR_SIGN_NOT_MODIFY", "签名不支持修改", ""),
        ;

        private String code;
        private String message;
        private String simpleMessage;

        AliMsgResultEnum(String code, String message, String simpleMessage) {
            this.code = code;
            this.message = message;
            this.simpleMessage = simpleMessage;
        }

        public String getCode() {
            return code;
        }

        public String getMessage() {
            return message;
        }

        public String getSimpleMessage() {
            return simpleMessage;
        }

        public static String getMessageByCode(String code) {
            for (AliMsgResultEnum value : AliMsgResultEnum.values()) {
                if (value.getCode().equals(code)) {
                    return value.getMessage();
                }
            }
            return "";
        }

        public static String getSimpleMessageByCode(String code) {
            for (AliMsgResultEnum value : AliMsgResultEnum.values()) {
                if (value.getCode().equals(code)) {
                    return value.getSimpleMessage();
                }
            }
            return "";
        }
    }
}
